const db = require("@/db/index");

// 查询员工培训信息
exports.queryTraining = (req, resp) => {
  try {
    const {
      pageSize = 10,
      pageNum = 1,
      staffName,
      position,
      timeStart,
      timeEnd
    } = req.body;

    // 构建查询条件
    let conditions = [];
    let params = [];
    if (staffName) {
      conditions.push("staff_name LIKE ?");
      params.push(`%${staffName}%`);
    }
    if (position) {
      conditions.push("position LIKE ?");
      params.push(`%${position}%`);
    }
    if (timeStart && timeEnd) {
      // 确保时间格式正确
      conditions.push("time BETWEEN ? AND ?");
      params.push(timeStart, timeEnd);
    } else if (timeStart) {
      // 只输入开始时间
      conditions.push("time >= ?");
      params.push(timeStart);
    } else if (timeEnd) {
      // 只输入结束时间
      conditions.push("time <= ?");
      params.push(timeEnd);
    }

    // 组装WHERE子句
    const whereClause =
      conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";

    // 查询总数
    const countSql = `SELECT COUNT(*) as total FROM employeetraining ${whereClause}`;
    db.query(countSql, params, (err, totalResult) => {
      if (err) return resp.err(err);
      const total = totalResult[0].total;

      // 查询数据
      const offset = (pageNum - 1) * pageSize;
      const dataSql = `
                  SELECT * FROM employeetraining 
                  ${whereClause} 
                  ORDER BY create_time DESC 
                  LIMIT ? OFFSET ?
              `;

      db.query(dataSql, [...params, pageSize, offset], (err, rows) => {
        if (err) return resp.err(err);
        resp.ok({
          total,
          list: rows,
          pageSize,
          pageNum,
        });
      });
    });
  } catch (error) {
    resp.err(error);
  }
};

// 添加员工培训信息
exports.addTraining = (req, resp) => {
  try {
    const trainingInfo = req.body;

    // 验证必填字段
    if (!trainingInfo.staff_no) return resp.err("员工工号不能为空");
    if (!trainingInfo.staff_name) return resp.err("员工姓名不能为空");
    if (!trainingInfo.position) return resp.err("职位不能为空");
    if (!trainingInfo.department_name) return resp.err("部门名称不能为空");
    if (!trainingInfo.time) return resp.err("培训时间不能为空");
    if (!trainingInfo.content) return resp.err("培训内容不能为空");
    if (!trainingInfo.place) return resp.err("培训地点不能为空");
    if (!trainingInfo.duration) return resp.err("培训时长不能为空");

    // 计算结束时间
    const startTime = new Date(trainingInfo.time);
    const durationHours = parseInt(trainingInfo.duration);
    const endTime = new Date(
      startTime.getTime() + durationHours * 60 * 60 * 1000
    );

    // 构建插入数据
    const insertData = {
      staff_no: trainingInfo.staff_no,
      staff_name: trainingInfo.staff_name,
      position: trainingInfo.position,
      sex: trainingInfo.sex || null,
      age: trainingInfo.age || null,
      department_name: trainingInfo.department_name,
      time: trainingInfo.time,
      content: trainingInfo.content,
      place: trainingInfo.place,
      duration: trainingInfo.duration,
      end_time: endTime,
      remarks: trainingInfo.remarks || null,
    };

    // 插入数据
    const insertSql = "INSERT INTO employeetraining SET ?";
    db.query(insertSql, insertData, (err, result) => {
      if (err) {
        console.error("添加员工培训信息失败:", err);
        return resp.err("添加失败: " + err.message);
      }
      if (result.affectedRows !== 1) return resp.err("添加失败");
      resp.ok(
        { id: result.insertId, ...insertData, create_time: new Date() },
        "添加成功"
      );
    });
  } catch (error) {
    console.error("添加异常:", error);
    resp.err("添加失败: " + error.message);
  }
};

// 删除员工培训信息
exports.deleteTraining = (req, resp) => {
  try {
    const { ids } = req.body;

    // 验证ID列表
    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return resp.err("ID列表不能为空");
    }

    // 删除数据
    const deleteSql = "DELETE FROM employeetraining WHERE id IN (?)";
    db.query(deleteSql, [ids], (err, result) => {
      if (err) {
        console.error("删除失败:", err);
        return resp.err("删除失败: " + err.message);
      }
      if (result.affectedRows === 0) return resp.err("未找到记录");
      resp.ok(
        { deletedCount: result.affectedRows },
        `成功删除${result.affectedRows}条`
      );
    });
  } catch (error) {
    console.error("删除异常:", error);
    resp.err("删除失败: " + error.message);
  }
};

// 更新员工培训信息
exports.updateTraining = (req, resp) => {
  try {
    const trainingInfo = req.body;

    // 验证ID必填
    if (!trainingInfo.id) return resp.err("ID不能为空");

    // 重新计算结束时间
    if (trainingInfo.time && trainingInfo.duration) {
      const startTime = new Date(trainingInfo.time);
      const durationHours = parseInt(trainingInfo.duration);
      trainingInfo.end_time = new Date(
        startTime.getTime() + durationHours * 60 * 60 * 1000
      );
    }

    // 更新数据
    const updateSql = "UPDATE employeetraining SET ? WHERE id = ?";
    db.query(updateSql, [trainingInfo, trainingInfo.id], (err, result) => {
      if (err) {
        console.error("更新失败:", err);
        return resp.err("更新失败: " + err.message);
      }
      if (result.affectedRows === 0) return resp.err("未找到记录");

      // 查询更新后的数据
      const selectSql = "SELECT * FROM employeetraining WHERE id = ?";
      db.query(selectSql, [trainingInfo.id], (err, rows) => {
        if (err) {
          console.error("查询失败:", err);
          return resp.err("查询失败: " + err.message);
        }
        if (rows.length === 0) return resp.err("未找到记录");
        resp.ok(rows[0], "更新成功");
      });
    });
  } catch (error) {
    console.error("更新异常:", error);
    resp.err("更新失败: " + error.message);
  }
};
